import { LoggerModule as PinoLoggerModule } from 'nestjs-pino';
import { Module } from '@nestjs/common';
import { join } from 'path';
import { ConfigModule, ConfigService } from '@nestjs/config';

@Module({
  imports: [
    PinoLoggerModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: () => {
        const infoTargetsOption = {
          level: 'info',
          target: 'pino-roll',
          options: {
            file: join('logsPino', 'log.info.log'), // 日志输出文件位置
            frequency: 'daily',
            size: '5m', // 文件滚动，日志文件不会超过5m
            mkdir: true, // 自动创建文件夹
          },
        };

        const errorTargetsOption = {
          level: 'error',
          target: 'pino-roll',
          options: {
            file: join('logsPino', 'log.error.log'), // 日志输出文件位置
            frequency: 'daily',
            size: '5m', // 文件滚动，日志文件不会超过5m
            mkdir: true, // 自动创建文件夹
          },
        };

        // 通过环境变量判断，如果需要开启日志就加到数组中
        const targets = [infoTargetsOption, errorTargetsOption];

        return {
          pinoHttp: {
            transport: {
              targets,
            },
          },
        };
      },
    }),
  ],
})
export class LoggerModule {}
